package com.vogue.supplymall.admin.business.domain.biz.impl;

import com.vogue.supplymall.account.domain.model.AdminUser;
import com.vogue.supplymall.admin.business.domain.biz.OrganManagementBiz;
import com.vogue.supplymall.admin.business.domain.model.AdminAccountBalance;
import com.vogue.supplymall.admin.business.domain.model.AdminAccountDiscount;
import com.vogue.supplymall.admin.business.domain.model.AdminCheckLicence;
import com.vogue.supplymall.admin.business.domain.model.AdminConsumeProduct;
import com.vogue.supplymall.admin.business.domain.model.AdminPlatform;
import com.vogue.supplymall.admin.business.domain.model.AdminRecharge;
import com.vogue.supplymall.admin.business.domain.service.AdminAccountBalanceService;
import com.vogue.supplymall.admin.business.domain.service.AdminAccountDiscountService;
import com.vogue.supplymall.admin.business.domain.service.AdminCheckLicenceService;
import com.vogue.supplymall.admin.business.domain.service.AdminConsumeProductService;
import com.vogue.supplymall.admin.business.domain.service.AdminPlatformService;
import com.vogue.supplymall.admin.business.domain.service.AdminRechargeService;
import com.vogue.supplymall.common.domain.dto.admin.OrganManagementInfo;
import com.vogue.supplymall.common.domain.dto.admin.PlatformInfo;
import com.vogue.supplymall.cross.domain.service.AdminManagementService;
import com.vogue.supplymall.match.domain.service.MatchOrganService;
import com.vogue.supplymall.shop.domain.service.ShopService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * The type Organ management biz.
 * 集团管理的biz
 *
 * @author zhangliang
 * Create in 2018-06-08
 */
@Service("organManagementBiz")
public class OrganManagementBizImpl implements OrganManagementBiz {
    /**
     * The constant log.
     */
    public static final Logger LOGGER_ORGANMANAGEMENTBIZIMPL = LoggerFactory.getLogger(OrganManagementBizImpl.class);
    @Resource
    private AdminManagementService adminManagementService;
    @Resource
    private AdminCheckLicenceService adminCheckLicenceService;
    @Resource
    private AdminAccountBalanceService adminAccountBalanceService;
    @Resource
    private AdminRechargeService adminRechargeService;
    @Resource
    private AdminAccountDiscountService adminAccountDiscountService;
    @Resource
    private AdminConsumeProductService adminConsumeProductService;
    @Resource
    private AdminPlatformService adminPlatformService;
    @Resource
    private ShopService shopService;
    @Resource
    private MatchOrganService matchOrganService;


    @Override
    public Map<String, Object> getOrganList(OrganManagementInfo managementInfo) {
        return adminManagementService.findOpenedOrgan(managementInfo);
    }

    @Override
    @Transactional
    public void doOnOffOrgan(OrganManagementInfo managementInfo) {
        // 保存要开通的申请信息
        AdminCheckLicence adminCheckLicence = adminCheckLicenceService.get(managementInfo.getSyscodeid());
        if (null == adminCheckLicence) {
            adminCheckLicence = new AdminCheckLicence();
            adminCheckLicence.setId(managementInfo.getSyscodeid());
            adminCheckLicence.setApplyid(0L);
            adminCheckLicence.setMatchid("0");
            adminCheckLicence.setShopid(0L);
            adminCheckLicence.setSyscodeid(managementInfo.getSyscodeid());
            adminCheckLicence.setOnoff(managementInfo.getOnoff());
            adminCheckLicence.setType(1);
            adminCheckLicenceService.save(adminCheckLicence);
        } else {
            adminCheckLicence.setOnoff(managementInfo.getOnoff());
            adminCheckLicence.setDisabledflag(false);
            adminCheckLicence.setModifyDate(new Date());
            adminCheckLicenceService.update(adminCheckLicence);
        }
    }

    @Override
    public List<Map<String, Object>> searchAccountBook(Long organid) {
        LOGGER_ORGANMANAGEMENTBIZIMPL.info("查询账本信息 start");
        String sql = "select aab1.id balanceId,aab1.organid,aab1.consumeid,aab1.balance,aab2.balance creditLimit "
                + " from admin_account_balance aab1 INNER JOIN admin_account_balance aab2 on (aab1.organid = aab2.organid) "
                + " where aab1.organid = #{organid} and aab1.type = 0 and aab2.type = 1";
        Map<String, Object> para = new HashMap<>();
        para.put("organid", organid);
        List<Map<String, Object>> result = adminAccountBalanceService.query0(sql, para);
        LOGGER_ORGANMANAGEMENTBIZIMPL.info("查询账本信息 end 结果件数：" + result.size());
        if (result.size() <= 0) {
            return null;
        }
        return result;
    }

    @Override
    @Transactional
    public void doOrganRecharge(OrganManagementInfo managementInfo, AdminUser userInfo) {
        LOGGER_ORGANMANAGEMENTBIZIMPL.info("集团充值处理开始 start");
        AdminRecharge recharge = new AdminRecharge();
        recharge.setConsumeid(managementInfo.getConsumeid());
        recharge.setSyscodeid(managementInfo.getSyscodeid());
        recharge.setOrganid(managementInfo.getOrganid());
        recharge.setAmount(new BigDecimal(managementInfo.getAmount()));
        recharge.setUpdateuser(userInfo.getLoginname());
        recharge.setUpdateuserid(userInfo.getId());
        recharge = adminRechargeService.save(recharge);
        LOGGER_ORGANMANAGEMENTBIZIMPL.info("添加充值信息 id：" + recharge.getId() + "; 充值金额：" + recharge.getAmount());
        BigDecimal total = recharge.getAmount();
        if (StringUtils.isNotEmpty(managementInfo.getDiscount())) {
            AdminAccountDiscount discount = new AdminAccountDiscount();
            discount.setAmount(new BigDecimal(managementInfo.getDiscount()));
            discount.setRechargeid(recharge.getId());
            discount.setConsumeid(managementInfo.getConsumeid());
            discount.setOrganid(managementInfo.getOrganid());
            discount.setSyscodeid(managementInfo.getSyscodeid());
            discount.setType(0);
            discount.setUpdateuser(userInfo.getLoginname());
            discount.setUpdateuserid(userInfo.getId());
            discount = adminAccountDiscountService.save(discount);
            LOGGER_ORGANMANAGEMENTBIZIMPL.info("添加优惠信息 id：" + discount.getId() + "; 优惠金额：" + discount.getAmount());
            total = total.add(discount.getAmount());
        }

        // 更新账本
        AdminAccountBalance balance = adminAccountBalanceService.get(managementInfo.getBalanceId());
        if (null == balance) {
            throw new RuntimeException();
        }
        total = balance.getBalance().add(total);
        balance.setBalance(total);
        balance.setUpdateuser(userInfo.getLoginname());
        balance.setUpdateuserid(userInfo.getId());
        balance.setModifyDate(new Date());
        adminAccountBalanceService.update(balance);
        LOGGER_ORGANMANAGEMENTBIZIMPL.info("更新账本信息信息 id：" + balance.getId() + "; 账本余额：" + balance.getBalance());
        LOGGER_ORGANMANAGEMENTBIZIMPL.info("集团充值处理开始 end");
    }

    @Override
    public Map<String, Object> searchConsumeConfig(OrganManagementInfo managementInfo) {
        LOGGER_ORGANMANAGEMENTBIZIMPL.info("检索消费配置信息 start");
        String sql = "SELECT "
                + " ao.id organid,acp.id consumeid,aab1.id balanceid,acp.consumetype,acp.cost,acp.owner,"
                + " acp.commission,acp.singleratio,acp.upperlimit,acp.minimum,acp.validtype,acp.memo,"
                + " aab.balance,aab1.balance creditLimit "
                + " FROM"
                + " admin_organ ao"
                + " INNER JOIN admin_consume_product acp ON (ao.id = acp.organid)"
                + " INNER JOIN admin_account_balance aab ON (acp.organid = aab.organid and aab.type = 0) "
                + " INNER JOIN admin_account_balance aab1 ON (acp.organid = aab1.organid and aab1.type = 1) "
                + " WHERE"
                + " ao.id = #{organid}";
        Map<String, Object> para = new HashMap<>();
        para.put("organid", managementInfo.getOrganid());
        List<Map<String, Object>> result = adminAccountBalanceService.query0(sql, para);
        Function<String, List<Map<String, Object>>> filterResult = (type) -> result.stream()
                .filter((map) -> type.equals(map.get("validtype").toString()))
                .collect(Collectors.toList());
        Map<String, Object> data = new HashMap<>();
        data.put("current", filterResult.apply("0"));
        data.put("renewal", filterResult.apply("1"));
        LOGGER_ORGANMANAGEMENTBIZIMPL.info("result size:" + result.size());
        LOGGER_ORGANMANAGEMENTBIZIMPL.info("检索消费配置信息 end");
        return data;
    }

    @Override
    @Transactional
    public void updateConsumeConfig(OrganManagementInfo info, AdminUser userInfo) {
        LOGGER_ORGANMANAGEMENTBIZIMPL.info(" 改配处理 start ");
        LOGGER_ORGANMANAGEMENTBIZIMPL.info(" 更新计费产品信息 start ");
        if (null == info.getConsumeid()) {
            AdminConsumeProduct product = new AdminConsumeProduct();
            setConsumeProduct(info, userInfo, product);
            product.setOrganid(info.getOrganid());
            product.setSyscodeid(info.getSyscodeid());
            adminConsumeProductService.save(product);
        } else {
            AdminConsumeProduct product = adminConsumeProductService.get(info.getConsumeid());
            setConsumeProduct(info, userInfo, product);
            product.setModifyDate(new Date());
            adminConsumeProductService.update(product);
        }
        LOGGER_ORGANMANAGEMENTBIZIMPL.info(" 更新计费产品信息 end ");

        if (StringUtils.isNotEmpty(info.getCreditLimit())) {
            LOGGER_ORGANMANAGEMENTBIZIMPL.info(" 更新账本的信用额度信息 start ");
            AdminAccountBalance balance = adminAccountBalanceService.get(info.getBalanceId());
            balance.setBalance(new BigDecimal(info.getCreditLimit()));
            balance.setModifyDate(new Date());
            adminAccountBalanceService.update(balance);
            LOGGER_ORGANMANAGEMENTBIZIMPL.info(" 更新账本的信用额度信息 end ");
        }

        // 更新集团入住平台基本信息
        String sql = " organid = #{organid} and disabledflag = 0 ";
        Map<String, Object> para = new HashMap<>();
        para.put("organid", info.getOrganid());
        List<AdminPlatform> oldRes = adminPlatformService.selectByWhr0(sql, para);
        final List<PlatformInfo> newRes = info.getPlatformInfo();

        for (PlatformInfo addPlatform : newRes) {
            List<AdminPlatform> isAdd = oldRes.parallelStream()
                    .filter((oldRe) -> addPlatform.getChannel().toString().equals(oldRe.getPlatform().toString()))
                    .collect(Collectors.toList());

            if (isAdd.size() == 0) {
                AdminPlatform adminPlatform = new AdminPlatform();
                adminPlatform.setIsbind(addPlatform.getIsbind());
                adminPlatform.setOrganid(info.getOrganid());
                adminPlatform.setSyscodeid(info.getSyscodeid());
                adminPlatform.setPlatform(Integer.valueOf(addPlatform.getChannel()));
                adminPlatform.setUpdateuser(userInfo.getLoginname());
                adminPlatform.setUpdateuserid(userInfo.getId());
                LOGGER_ORGANMANAGEMENTBIZIMPL.info("保存集团入住平台基本信息，syscodeid:" + info.getSyscodeid());
                adminPlatformService.save(adminPlatform);
            }
        }

        boolean i;
        List<AdminPlatform> removeQue = new ArrayList<>();
        for (AdminPlatform old : oldRes) {
            i = true;
            for (PlatformInfo fresh : newRes) {
                if (old.getPlatform().toString().equals(fresh.getChannel().toString())) {
                    i = false;
                    break;
                }
            }
            if (i) {
                removeQue.add(old);
            }
        }

        for (AdminPlatform delPlatform : removeQue) {
            delPlatform.setDisabledflag(true);
            delPlatform.setModifyDate(new Date());
            adminPlatformService.update(delPlatform);
            LOGGER_ORGANMANAGEMENTBIZIMPL.info("删除集团入住平台基本信息，syscodeid:" + info.getSyscodeid());
        }

        // 关闭不展示平台的集团和店铺
        for (AdminPlatform platform : removeQue) {
            Map<String, Object> upPara = new HashMap<>();
            upPara.put("syscodeid", platform.getSyscodeid());
            upPara.put("tendid", platform.getPlatform());
            upPara.put("modifydate", new Date());
            String updateShopSql = "update shop set disabledflag = 1,modifydate = #{modifydate} "
                    + " where syscodeid = #{syscodeid} and tendid = #{tendid};";
            shopService.update0(updateShopSql, upPara);
            String updateMacthSql = "update match_organ set disabledflag = 1,modifydate = #{modifydate} "
                    + " where syscodeid = #{syscodeid} and tendid = #{tendid};";
            matchOrganService.update0(updateMacthSql, upPara);
        }

        LOGGER_ORGANMANAGEMENTBIZIMPL.info(" 改配处理 end ");
    }

    /**
     * 计费产品信息-设置插入或更新的参数
     *
     * @param info info
     * @param userInfo userInfo
     * @param adminBilling adminBilling
     */
    private void setConsumeProduct(OrganManagementInfo info, AdminUser userInfo, AdminConsumeProduct adminBilling) {

        // 如果计费产品类型是按单扣点
        if (info.getBillingtype() == 3) {
            adminBilling.setCost(BigDecimal.ZERO);
            adminBilling.setSingleratio(new BigDecimal(info.getSingleratio()));
            adminBilling.setMinimum(new BigDecimal(info.getMinimum()));
            adminBilling.setUpperlimit(new BigDecimal(info.getUpperlimit()));
        } else {
            adminBilling.setCost(new BigDecimal(info.getCost()));
            adminBilling.setSingleratio(BigDecimal.ZERO);
            adminBilling.setUpperlimit(BigDecimal.ZERO);
            adminBilling.setMinimum(BigDecimal.ZERO);
        }
        adminBilling.setConsumetype(info.getBillingtype());
        adminBilling.setOwner(info.getOwner());
        adminBilling.setDisabledflag(false);
        // 有效类型设置为续期
        adminBilling.setValidtype(1);
        adminBilling.setUpdateuser(userInfo.getLoginname());
        adminBilling.setUpdateuserid(userInfo.getId());
        adminBilling.setCommission(new BigDecimal(info.getCommission()));
        if (StringUtils.isNotEmpty(info.getMemo())) {
            adminBilling.setMemo(info.getMemo());
        } else {
            adminBilling.setMemo("");
        }
    }
}
